import { IFeidaoAiNodejsPage, IWebResult } from '../../interfaces';
import is_online from '../msg-b/user-isonline';
import storage_put from '../storage/put';
import generate from '../url/query2url';
import check_user from './check';

function generate_redirect(url: string, fallback: string) {
	const page_name = url.match(/.*\/((.*?)\.html)/)![1];
	const params = url.includes('?') ? url.substr(url.indexOf('?')) : '';
	const obj = {
		backurl: './' + page_name + params
	};
	return generate(obj, fallback);
}

/**
 * 检查用户权限
 * @param productid 产品id
 * @param client_type '2' h5 '3' web '9' 微信小程序
 * @param fallback 失败后跳转的页面路径，通常是登陆页或403错误页
 */
export default async function check(fd: IFeidaoAiNodejsPage, productid: string, client_type: '2' | '3' | '9', fallback: string) {
	const { actionid, sessionid, spaceid, msg, headers, url } = fd.data;
	const line = await is_online(actionid, sessionid, spaceid, msg);
	if (line) {
		const res = await check_user(msg, headers, productid, client_type);
		if (!res.result) {
			const redirect = generate_redirect(url, fallback);
			return {
				code: 0,
				redirect,
				status_code: 403
			} as IWebResult;
		} else {
			const auth_code = res.auth_code;
			await storage_put('auth_code', auth_code);
			return {} as IWebResult;
		}
	} else {
		const redirect = generate_redirect(url, fallback);
		return {
			code: 0,
			redirect
		} as IWebResult;
	}
}
